package com.seashop.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author moredln
 * @desc
 * @date 2020-10-28 17:02
 */
public class ReferralCodeUtil {

    public static String getReferralCode() {
        String code;
        do {
            code = generateCode();
        } while (!checkCode(code));
        return code;
    }

    private static String generateCode() {
        char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 8; i++) {
            code += chars[random.nextInt(10)];
        }
        return code;
    }

    private static boolean checkCode(String code) {
        if(matchStr(code, "aaaabbbb") || matchStr(code, "aaaaaaaa")) {
            return false;
        }
        return true;
    }

    public static boolean matchStr(String data, String pattern) {
        if (data == null || data.isEmpty() || pattern == null || pattern.isEmpty() || data.length() != pattern.length()) {
            return false;
        }

        Map<Character, String> reflect = new HashMap<>();
        String[] pieces = data.split("");
        if (pattern.length() != pieces.length) {
            return false;
        }

        for (int i = 0; i < pattern.length(); i++) {
            boolean isHaveKey = reflect.containsKey(pattern.charAt(i));
            boolean isHaveValue = reflect.containsValue(pieces[i]);
            String value = reflect.get(pattern.charAt(i));
            if (isHaveKey) {
                if (!value.equals(pieces[i])) {
                    return false;
                }
            } else {
                if (isHaveValue) {
                    return false;
                } else {
                    reflect.put(pattern.charAt(i), pieces[i]);
                }
            }
        }
        return true;
    }

}
